package com.lamp.downloadimage;

import android.graphics.Bitmap;

import java.lang.ref.SoftReference;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class BitmapCache {

	private static final int HARD_CACHE_CAPACITY = 50;

	private final HashMap<String, Bitmap> sHardBitmapCache = new LinkedHashMap<String, Bitmap>(
			HARD_CACHE_CAPACITY / 2, 0.75f, true) {
		@Override
		protected boolean removeEldestEntry(Map.Entry<String, Bitmap> eldest) {
			if (size() > HARD_CACHE_CAPACITY) {
				sSoftBitmapCache.put(eldest.getKey(),
						new SoftReference<Bitmap>(eldest.getValue()));
				return true;
			} else

				return false;
		}
	};

	private final static ConcurrentHashMap<String, SoftReference<Bitmap>> sSoftBitmapCache = new ConcurrentHashMap<String, SoftReference<Bitmap>>(
			HARD_CACHE_CAPACITY / 2);

	public void addBitmapToCache(String url, Bitmap bitmap) {
		if (bitmap != null) {
			synchronized (sHardBitmapCache) {
				sHardBitmapCache.put(url, bitmap);
			}
		}
	}

	public Bitmap getBitmapFromCache(String url) {
		if (url != null) {
			synchronized (sHardBitmapCache) {
				final Bitmap bitmap = sHardBitmapCache.get(url);
				if (bitmap != null) {
					sHardBitmapCache.remove(url);
					sHardBitmapCache.put(url, bitmap);
					return bitmap;
				}
			}

			SoftReference<Bitmap> bitmapReference = sSoftBitmapCache.get(url);
			if (bitmapReference != null) {
				final Bitmap bitmap = bitmapReference.get();
				if (bitmap != null) {
					return bitmap;
				} else {
					sSoftBitmapCache.remove(url);
				}
			}
		}
		return null;
	}

	public void clear() {
		synchronized (sHardBitmapCache) {
			sHardBitmapCache.clear();
		}
	}
}
